package com.ak.server.platform.controller;

import com.ak.common.annotation.LogEndpoint;
import com.ak.common.controller.BaseController;
import com.ak.common.entity.AKResponse;
import com.ak.common.entity.Enums;
import com.ak.common.entity.QueryRequest;
import com.ak.common.entity.system.Application;
import com.ak.common.entity.system.Datasource;

import com.ak.common.entity.system.DatasourceApplication;
import com.ak.common.entity.system.TenantApplication;
import com.ak.common.utils.EnumUtil;
import com.ak.common.utils.StringUtil;
import com.ak.server.platform.service.IApplicationService;
import com.ak.server.platform.service.IDatasourceApplicationService;
import com.ak.server.platform.service.IDatasourceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 数据源管理
 *
 * @author Van
 * @date 2019-06-23
 */
@Api(tags = "数据源模块")
@RestController
@RequestMapping("datasource")
public class DatasourceController extends BaseController {

    @Resource
    private IDatasourceService dataSourceService;

    @Resource
    private IDatasourceApplicationService datasourceApplicationService;

    @Autowired
    private IApplicationService applicationService;


    @ApiOperation("查询数据源集合")
    @LogEndpoint(operation = "查询数据源集合")
    @GetMapping
    public AKResponse list(QueryRequest queryRequest, Datasource datasource) {
        datasource.setDelFlag(Enums.DelFlag.EXIST.getCode());
        Map<String, Object> dataTable = StringUtil.getDataTable(dataSourceService.selectDatasourceList(datasource, queryRequest));
        return new AKResponse().data(dataTable);

    }

    @ApiOperation("获取数据源编码")
    @GetMapping("getDatasourceCode")
    public AKResponse getDatasourceCode() {
        return new AKResponse().data(StringUtil.random(8, Enums.RandomType.STRING));
    }

    @ApiOperation("查询数据库类型枚举")
    @GetMapping("/getDatabaseType")
    public AKResponse getDatabaseType() {
        Map<String, String> map = EnumUtil.EnumToMap(Enums.DatabaseType.class);
        return new AKResponse().data(map);
    }

    @ApiOperation("查询数据库标识枚举")
    @GetMapping("/getDatabaseFlag")
    public AKResponse getDatabaseFlag() {
        Map<String, String> map = EnumUtil.EnumToMap(Enums.DatabaseFlag.class);
        return new AKResponse().data(map);
    }

    /**
     * 新增数据源
     */
    @ApiOperation("添加数据源")
    @LogEndpoint(operation = "添加数据源")
    @PostMapping
    public AKResponse add(@Validated Datasource datasource) {
        datasource.setCreateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        datasource.setCreateTime(new Date());
        return new AKResponse().data(dataSourceService.save(datasource));
    }


    /**
     * 修改数据源
     */
    @ApiOperation("更新数据源")
    @LogEndpoint(operation = "更新数据源")
    @PutMapping
    public AKResponse update(@Validated Datasource datasource) {
        datasource.setUpdateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        datasource.setUpdateTime(new Date());
        return new AKResponse().data(dataSourceService.updateById(datasource));
    }

    /**
     * 删除数据源
     */
    @ApiOperation("删除数据源")
    @LogEndpoint(operation = "删除数据源")
    @DeleteMapping("/{id}")
    public AKResponse remove(@PathVariable("id") String id) {
        Datasource datasource = new Datasource();
        datasource.setDatasourceId(id).setDelFlag(Enums.DelFlag.DEL.getCode());
        return new AKResponse().data(dataSourceService.updateById(datasource));
    }


    @ApiOperation("获取用于分配的子系统")
    @GetMapping("/getAuthApplications/{tenantCode}/{datasourceCode}")
    public AKResponse getAuthApplications(@PathVariable("tenantCode") String tenantCode, @PathVariable("datasourceCode") String datasourceCode) {
        JSONObject result = new JSONObject();

        // 所有的
        JSONArray all = new JSONArray();
        all.addAll(applicationService.selectApplicationsByTenantCode(tenantCode));
        // 已分配的
        JSONArray exist = new JSONArray();
        exist.addAll(datasourceApplicationService.list(Wrappers.query(new DatasourceApplication().setDatasourceCode(datasourceCode))));

        result.put("all", all);
        result.put("exist", exist);
        return new AKResponse().data(result);
    }

    @ApiOperation("分配子系统")
    @PutMapping("/authApplication")
    @ResponseBody
    public boolean authApplication(String datasourceCode, String appCodes) {
        return datasourceApplicationService.authApplication(datasourceCode, appCodes);
    }
}
